package sctu.edu.java.year2016.team01.xuhanmei.day20160607;

import javax.swing.*;
import java.awt.*;
import java.util.Random;

/**
 * Created by Administrator on 2016/6/7.
 */
public class SleepMethodTest extends JFrame {
    private Thread t;
    private static Color[] color = {Color.PINK, Color.BLUE, Color.white, Color.cyan, Color.gray,
            Color.green, Color.orange, Color.yellow};
    private static final Random rand = new Random();//创建随机对象

    private static Color getC() {
        return color[rand.nextInt(color.length)];//获取随机颜色的方法
    }

    public SleepMethodTest() {
        t = new Thread(new Runnable() {
            int x = 500;//定义初始坐标
            int y = 500;

            @Override
            public void run() {
                while (true) {
                    try {
                        t.sleep(100);//休眠0.1秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Graphics graphics = getGraphics();//获取组件绘图上下文对象
                    graphics.setColor(getC());//设置绘图颜色
                    graphics.drawLine(x,y,100,y++);//绘制直线并递增垂直坐标
                    if (y >= 200) {

                        y = 160;
                    }
                }
            }


        });
        t.start();

    }

    public static void main(String[] args) {
        init(new SleepMethodTest(), 100, 100);
    }

    private static void init(JFrame frame, int width, int height) {//初始化程序界面的方法
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(width, height);
        frame.setVisible(true);
    }

}
